# python 3.8
import json
import urllib.request
import time
from datetime import datetime

import pymysql

import Configurations
import Encryptor

# ——获取配置信息——
# 数据库相关
DB_HOST = Configurations.dbHost
DB_PORT = int(Configurations.dbPort)
DB_USER = Configurations.dbUser
DB_PASSWORD = Configurations.dbPassword
DB_DBNAME = Configurations.dbName

# 加密相关
ENCIPHER_KEY = Configurations.objectiveKey
ENCIPHER_IV = Configurations.objectiveIV

# 发送目标服务器相关
OBJECTIVE_URL = 'https://' + Configurations.objectiveIP + ':' + Configurations.httpsPort + '/' + Configurations.pushPath
HEADERS = {'Content-Type': 'application/json'}

# 基本时间格式
DATE_FORMAT = '%Y-%m-%d %H:%M:%S'


# ——从大数据中心获取所需数据——
def getRecentData():
    # 尝试连接数据
    conn = pymysql.connect(host=DB_HOST, user=DB_USER, password=DB_PASSWORD, database=DB_DBNAME, port=DB_PORT)
    # 获取数据库连接后的光标
    cursor = conn.cursor()
    # 执行SQL语句(查询)
    cursor.execute('SELECT code_id, code_value,receive_time  FROM monitor_data limit 100')
    # 获取执行结果
    result = cursor.fetchall()

    # 将结果转为json格式的报文
    # 获取当前时间并转为时间戳
    currentTime = datetime.now()
    currentTimeStamp = currentTime.timestamp()
    # print("currentTimeStamp: ", currentTimeStamp)
    # dateString = str(result[0][2])
    # print("dateString: ", dateString)
    # timeStamp = datetime.strptime(dateString, DATE_FORMAT).timestamp()
    # print("timeStamp: ", timeStamp)
    dataBegin = '{"gatewayId":"1667064567139213314","ts":' + '"' + str(int(currentTimeStamp * 1000)) + '",' + '"datas":['
    dataEnd = ']}'
    datas = ''
    for line in result:
        datas = datas + '{"quotaId":' + str(line[0]) + ',"value":"' + str(line[1]) + '"},'
    returnData = dataBegin + datas[:-1] + dataEnd
    print("dataCount: ", len(result))
    print("returnData:\n", returnData)

    # # （临时）记录发送数据
    # file = open('record.txt', "a", encoding="utf-8")
    # # 记录当前时间
    # currentTimeStr = datetime.now().strftime(DATE_FORMAT)
    # file.write("currentTime: " + currentTimeStr + '\n')
    # file.write("dateString: " + dateString + '\n')
    # file.write("timeStamp: " + str(timeStamp) + '\n')
    # file.write("firstRecord: " + str(result[0]) + '\n')
    # file.write("dataCount: " + str(len(result)) + '\n')
    # file.write("returnData:\n" + returnData + '\n\n')
    # file.close()

    # 执行SQL语句(清空表)
    cursor.execute('TRUNCATE TABLE monitor_data')

    cursor.close()
    conn.close()
    return returnData


# —— main ——
if __name__ == '__main__':
    while True:
        try:
            # 1.从大数据中心获取数据
            dataText = getRecentData()
            # 2.将明文加密
            encipheredText = Encryptor.encipher(dataText, ENCIPHER_KEY, ENCIPHER_IV)
            # # 解密
            # decipheredText = Encryptor.decipher(encipheredText, key, iv)
            # print("decipheredText: ", decipheredText)

            # 3.2 将密文通过https发送给省厅
            reportData = {
                "appId": Configurations.appID,
                "data": encipheredText,
                "extend1": "",
                "extend2": ""
            }
            # print("request:\n", reportData)
            # 将数据编码为json格式
            json_data = json.dumps(reportData)
            # 发送POST请求
            request = urllib.request.Request(OBJECTIVE_URL, data=json_data.encode(), headers=HEADERS)
            response = urllib.request.urlopen(request)

            # 读取响应内容
            response_data = response.read()
            print("Resoponse:\n", response_data)

            # # （临时）记录发送数据
            # file = open('record.txt', "a", encoding="utf-8")
            # file.write("Resoponse:\n", response_data)
            # file.close()

        except Exception as err:
            # 将异常信息写入日志文件log.txt中
            file = open('log.txt', "a", encoding="utf-8")
            file.write(str(datetime.now()) + ': ' + str(err) + '\n')
            file.close()

        # 间隔10s再进行下次发送
        time.sleep(10)
